// 查询appoint_schedule有记录就弹错误提示，所以后面进行完的预约一定要删除记录
<template>
	<view class="container">
		<!-- 咨询师信息卡片 -->
		<view class="consultant-card">
			<view class="card-header">
				<u-image :src="consultantInfo.avatar" width="120rpx" height="120rpx" shape="circle"></u-image>
				<view class="consultant-info">
					<text class="name">{{ consultantInfo.name }}</text>
					<text class="expertise">擅长：{{ consultantInfo.expertise }}</text>
					<text class="experience">从业经验：{{ consultantInfo.experience || 0 }}年</text>
				</view>
			</view>
		</view>

		<!-- 提示信息 -->
		<view class="notice-section">
			<u-icon name="info-circle" color="#6c8eef" size="24"></u-icon>
			<text class="notice-text">每天21:00放出次日空闲时间段</text>
		</view>

		<!-- 日期选择区域 -->
		<view class="date-section">
			<view class="section-title">选择日期</view>
			<view class="date-selector" @click="show = true">
				<u-icon name="calendar" color="#6c8eef" size="32"></u-icon>
				<text>{{ selectedDate || '请选择日期' }}</text>
			</view>
		</view>

		<!-- 日历组件 -->
		<u-calendar 
			:maxDate="maxDate" 
			:minDate="minDate" 
			:show="show" 
			:closeOnClickOverlay="true" 
			@close="handleClose"
			:defaultDate="defaultDate" 
			@confirm="confirm">
		</u-calendar>

		<!-- 时间段选择区域 -->
		<view class="time-section">
			<view class="section-title">选择时间段</view>
			<view class="time-description">每段咨询时间为50分钟，中间休息10分钟</view>
			<view class="time-options">
				<view class="time-option" 
					v-for="(slot, index) in day.timeMarks" 
					:key="index"
					:class="{
						reserved: day.reservedSlots.includes(slot) && day.isShow,
						appointed: day.reservedSlots.includes(slot) && day.isShow && day.appointedSlots.includes(slot),
						disabled: disabledSlots.includes(slot) || !day.isShow
					}"
					@click="!disabledSlots.includes(slot) && day.isShow ? handleTimeSlotClick(selectedDate, slot) : null">
					<text class="time-text">{{ slot }}</text>
					<text class="status-text" v-if="day.appointedSlots.includes(slot)">已预约</text>
				</view>
			</view>
		</view>

		<!-- 预约确认弹窗 -->
		<u-popup :show="popupVisible" mode="center">
			<view class="popup-content">
				<text class="popup-title">确认预约</text>
				<text class="popup-message">{{ popupMessage }}</text>
				<view class="popup-buttons">
					<u-button type="primary" @click="handleAppoint()">确定</u-button>
					<u-button type="default" @click="popupVisible = false">取消</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		data() {
			const today = new Date();
			const minD = new Date();
			minD.setDate(today.getDate()); // Minimum date set to 3 days ago
			const maxD = new Date();
			maxD.setDate(today.getDate() + 10); // Max imum date set to 10 days later

			return {
				day: {
					timeMarks: [
						"09:00-09:50",
						"10:00-10:50",
						"13:00-13:50",
						"14:00-14:50",
						"15:00-15:50",
						"16:00-16:50",
						"19:00-19:50",
						"20:00-20:50",
						"21:00-21:50",
						"22:00-22:50",
						"23:00-23:50"
					],
					reservedSlots: [], // No reservations by default, updated onShow
					appointedSlots: [],
					isShow: ''
				},
				consultantUniIdToken: '',
				consultantInfo: {},
				show: false,
				selectedDate: '', // Selected date
				minDate: `${minD.getFullYear()}-${(minD.getMonth() + 1).toString().padStart(2, '0')}-${minD.getDate().toString().padStart(2, '0')}`,
				maxDate: `${maxD.getFullYear()}-${(maxD.getMonth() + 1).toString().padStart(2, '0')}-${maxD.getDate().toString().padStart(2, '0')}`,
				defaultDate: '',
				popupVisible: false, // Controls u-popup visibility
				selectedSlot: "", // Stores clicked timeslot
				popupMessage: "",
				currentTime: new Date(), // 记录当前时间，把已经经过的时间以及半小时以前设为灰色
				openid: ''
			};
		},
		onLoad(options) {
			this.consultantUniIdToken = options.uniIdToken;
			this.getConsultantInfo();
			this.setTodayAsDefault();
			this.getOpenId();
		},
		onShow() {
		    this.updateCurrentTime(); // 进入页面时更新当前时间
		    setInterval(this.updateCurrentTime, 60000); // 每分钟更新一次
		},
		computed: {
		    // 获取禁用的时间段
		      disabledSlots() {
		        if (!this.selectedDate) return [];
		      
		        const today = this.getToday();
		        if (this.selectedDate !== today) return [];
		      
		        // 当前时间 + 30 分钟
		        const bufferTime = new Date(this.currentTime.getTime() + 30 * 60000);
		      
		        // 获取禁用的时间段
		        return this.day.timeMarks.filter(time => {
		          const [startHour, startMinute] = time.split('-')[0].split(':').map(Number);
		          const slotStartTime = new Date();
		          slotStartTime.setHours(startHour, startMinute, 0, 0);
		      
		          // 判断该时段是否没有预定并且已经过了
		          return (
		            !this.day.reservedSlots.includes(time) ||  // 如果时段没有预定
		            slotStartTime <= bufferTime  // 如果时段已经过了当前时间 + 30 分钟
		          );
		        });
		      },

		},

		methods: {
			async getOpenId() {
				const res = await uniCloud.callFunction({
					name: "getOpenId",
					data: {
						uniIdToken: uni.getStorageSync('uni_id_token'),
					}
				});
				if (res.result.code === 0) { 
					this.openid = res.result.openid;
				} else {
					console.error("获取openid失败:", res.result.msg);
				}
			},
			onPullDownRefresh() {
					// 下拉时触发的刷新逻辑
					this.updateReservedSlots().then(() => {
						// 停止下拉刷新动画
						uni.stopPullDownRefresh();
						uni.showToast({
							title: '刷新成功',
							icon: 'success'
						});
					}).catch(() => {
						uni.stopPullDownRefresh();
						uni.showToast({
							title: '刷新失败',
							icon: 'none'
						});
					});
				},
			updateCurrentTime() {
			        this.currentTime = new Date();
			    },
			async getConsultantInfo() {
				const res = await uniCloud.callFunction({
					name: "getConsultantInfo",
					data: {
						uniIdToken: this.consultantUniIdToken,
					}
				});
				if (res.result.code === 0) { // 这里应该用 code 而不是 success
					this.consultantInfo = res.result.data;
				} else {
					console.error("获取咨询师信息失败:", res.result.message);
				}
			},
			handleClose() {
				console.log("日历关闭");
				this.show = false; // 手动隐藏日历
			},
			getToday() {
				const date = new Date();
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`; // Format as YYYY-MM-DD
			},
			setTodayAsDefault() {
				const today = this.getToday();
				this.selectedDate = today; // Set selected date to today
				this.defaultDate = today; // Set calendar default date
				this.updateReservedSlots(); // Update reserved timeslots for the day
			},
			confirm(e) {
				this.selectedDate = e[0]; // Selected date
				this.show = false;
				this.updateReservedSlots(); // Update timeslots
			},
			async updateReservedSlots() {
				try {
					const res1 = await uniCloud.callFunction({
						name: "getUserFreeSlots",
						data: {
							uniIdToken: this.consultantUniIdToken,
						}
					});

					if (res1.result.success) {
						const freeSlotData = res1.result.reservations.find(item => item.day === this.selectedDate) || {};
						console.log('ihoihoihok',freeSlotData)
						this.day.isShow = freeSlotData.isShow; 
						this.day.reservedSlots = freeSlotData.freeSlots || [];
					}

					const res2 = await uniCloud.callFunction({
						name: "getConsultantAppointSlots",
						data: {
							uniIdToken: this.consultantUniIdToken,
						}
					});

					if (res2.result.success) {
						this.day.appointedSlots = []; // 先清空，避免重复添加
						res2.result.appoint
							.filter(item => item.day === this.selectedDate)
							.forEach(item => {
								if (item.appointedSlot) {
									this.day.appointedSlots.push(item.appointedSlot);
								}
							});
					}
				} catch (error) {
					console.error("获取预约信息失败:", error);
					uni.showToast({
						title: "获取预约信息失败",
						icon: "none"
					});
				}
			},

			handleTimeSlotClick(date, slot) {
				// 检查是否是已预约的时段
					if (this.day.appointedSlots.includes(slot)) {
						uni.showToast({
							title: "已预约时段，若要取消请到预约列表操作",
							icon: "none"
						});
						return; // 阻止弹出预约弹窗
					}
				 if (this.disabledSlots.includes(slot)) return;
				this.selectedSlot = slot;

				this.popupVisible = true; // Show set free slot popup
				this.popupMessage = `确定预约 ${this.selectedDate} 的 ${this.selectedSlot} 进行心理咨询？`;
			},
			async handleAppoint() {
			    try {
					
			        let res;
			            // 创建预约
			            res = await uniCloud.callFunction({
			                name: "createAppointment",
			                data: {
			                    uniIdToken: uni.getStorageSync('uni_id_token'),
			                    consultantUniIdToken: this.consultantUniIdToken, 
			                    day: this.selectedDate,
			                    appointedSlot: this.selectedSlot
			                }
			            });
			
			        // 统一处理成功或失败
			        if (res.result.success) {
						
						uni.requestSubscribeMessage({
						  tmplIds: ['lpbzb9GviTD0yJ0woys9ijVx3mp2WIDwQcQYX-FPa64'], // 模板 ID
						  success: (res) => {
						    console.log('订阅返回结果：', res);
						    
						    // 判断用户是否同意订阅
						    if (res['lpbzb9GviTD0yJ0woys9ijVx3mp2WIDwQcQYX-FPa64'] === 'accept') {
						      // 用户同意订阅
						      console.log('用户同意订阅');
						
						      // 更新用户订阅状态为已订阅
						      uniCloud.callFunction({
						        name: 'updateSubscriptionStatus', // 云函数名称
						        data: {
						          uniIdToken: uni.getStorageSync('uni_id_token'),
						          hasSubscribed: true // 设置为已订阅
						        },
						        success: (res2) => {
						          console.log('订阅状态更新成功:', res2);
						        },
						        fail(err) {
						          console.error('更新订阅状态失败：', err);
						        }
						      });
						    } else if (res['lpbzb9GviTD0yJ0woys9ijVx3mp2WIDwQcQYX-FPa64'] === 'reject') {
						      // 用户拒绝订阅
						      console.log('用户拒绝订阅');
						
						      // 更新用户订阅状态为未订阅
						      uniCloud.callFunction({
						        name: 'updateSubscriptionStatus',
						        data: {
						          uniIdToken: uni.getStorageSync('uni_id_token'),
						          hasSubscribed: false // 设置为未订阅
						        },
						        success(res2) {
						          console.log('订阅状态更新成功:', res2);
						        },
						        fail(err) {
						          console.error('更新订阅状态失败：', err);
						        }
						      });
						    }
						  },
						  fail(err) {
						    console.log('请求失败：', err);
						  }
						});


						
			            uni.showToast({
			                title: this.isCancelAction ? "预约已取消" : "预约成功",
			                icon: "success"
			            });
			            this.popupVisible = false;
			            this.updateReservedSlots();
			        } else {
			            // 如果失败，检查返回的错误信息并弹出 toast
			            console.error("预约失败:", res.result);
			            if (res.result.message) {
			                uni.showToast({
			                    title: res.result.message, // 显示返回的错误信息
			                    icon: "none"
			                });
			            } else {
			                uni.showToast({
			                    title: "预约失败",
			                    icon: "none"
			                });
			            }
			        }
			    } catch (error) {
			        console.error("预约失败:", error);
			        uni.showToast({
			            title: "预约失败",
			            icon: "none"
			        });
			    }
			
			    // 只刷新时间轴，关闭弹窗
			    this.popupVisible = false;
			    this.updateReservedSlots();
			}

	}
	};
</script>

<style lang="scss">
	/* 全局变量 */
	:root {
		--primary-color: #6c8eef;
		--primary-hover: #5a7de0;
		--secondary-color: #f8f9fa;
		--text-color: #2c3e50;
		--border-color: #dee2e6;
		--shadow-sm: 0 4rpx 8rpx rgba(0,0,0,0.05);
		--shadow-md: 0 8rpx 12rpx rgba(0,0,0,0.1);
		--shadow-lg: 0 16rpx 32rpx rgba(0,0,0,0.1);
		--radius-sm: 16rpx;
		--radius-md: 24rpx;
		--radius-lg: 32rpx;
		--spacing-sm: 16rpx;
		--spacing-md: 32rpx;
		--spacing-lg: 48rpx;
	}

	.container {
		min-height: 100vh;
		background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
		padding: 30rpx;
	}

	.consultant-card {
		background: white;
		border-radius: 24rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		box-shadow: var(--shadow-md);

		.card-header {
			display: flex;
			align-items: center;
			gap: 30rpx;
		}

		.consultant-info {
			flex: 1;
			display: flex;
			flex-direction: column;
			gap: 12rpx;

			.name {
				font-size: 36rpx;
				font-weight: 600;
				color: var(--text-color);
			}

			.expertise {
				font-size: 28rpx;
				color: #666;
			}

			.experience {
				font-size: 26rpx;
				color: #999;
			}
		}
	}

	.notice-section {
		display: flex;
		align-items: center;
		background-color: #f0f4ff;
		padding: 16rpx 24rpx;
		margin: 16rpx 30rpx;
		border-radius: 8rpx;
	}

	.notice-text {
		font-size: 24rpx;
		color: #6c8eef;
		margin-left: 8rpx;
	}

	.date-section {
		margin-bottom: 30rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: var(--text-color);
			margin-bottom: 20rpx;
		}

		.date-selector {
			background: white;
			border-radius: 24rpx;
			padding: 30rpx;
			display: flex;
			align-items: center;
			gap: 20rpx;
			box-shadow: var(--shadow-md);
			transition: all 0.3s ease;
			border: 2rpx solid var(--primary-color);

			&:active {
				transform: translateY(-2rpx);
				box-shadow: var(--shadow-lg);
			}

			text {
				font-size: 32rpx;
				color: var(--text-color);
			}
		}
	}

	.time-section {
		background: white;
		border-radius: 24rpx;
		padding: 30rpx;
		box-shadow: var(--shadow-md);

		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: var(--text-color);
			margin-bottom: 16rpx;
		}

		.time-description {
			font-size: 26rpx;
			color: #666;
			margin-bottom: 30rpx;
			padding-left: 20rpx;
			border-left: 4rpx solid var(--primary-color);
		}
	}

	.time-options {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(280rpx, 1fr));
		gap: 20rpx;
		padding: 10rpx;
	}

	.time-option {
		background: white;
		border: 2rpx solid var(--primary-color);
		border-radius: 16rpx;
		padding: 24rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		transition: all 0.3s ease;
		cursor: pointer;

		&:hover {
			transform: translateY(-2rpx);
			box-shadow: var(--shadow-md);
		}

		.time-text {
			font-size: 28rpx;
			color: var(--text-color);
			font-weight: 500;
		}

		.status-text {
			font-size: 24rpx;
			color: #ff4d4f;
		}

		&.reserved {
			background: rgba(108, 142, 239, 0.1);
			border-color: var(--primary-color);
		}

		&.appointed {
			background: rgba(255, 77, 79, 0.1);
			border-color: #ff4d4f;
		}

		&.disabled {
			background: #f5f5f5;
			border-color: #ddd;
			cursor: not-allowed;
			opacity: 0.6;

			.time-text {
				color: #999;
			}
		}
	}

	.popup-content {
		background: white;
		border-radius: 24rpx;
		padding: 40rpx;
		width: 600rpx;

		.popup-title {
			font-size: 36rpx;
			font-weight: 600;
			color: var(--text-color);
			margin-bottom: 20rpx;
			display: block;
		}

		.popup-message {
			font-size: 28rpx;
			color: #666;
			margin-bottom: 30rpx;
			display: block;
		}

		.popup-buttons {
			display: flex;
			gap: 20rpx;
			justify-content: flex-end;
		}
	}

	@media screen and (min-width: 690px) {
		.container {
			max-width: 800rpx;
			margin: 0 auto;
		}
	}
</style>